<template>
  <div class="app-container">
    <!-- v-permission="['eqt:smartversion:read']"
    v-permission="['eqt:smartversion:create']"
    更新 v-permission="['eqt:smartversion:read']"
    v-permission="['eqt:smartversion:read']"
    v-permission="['eqt:smartversion:delete']" -->
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model.trim="listQuery.fmac" clearable class="filter-item" style="width: 200px;" placeholder="请输入机器码"/>
      <el-input v-model.trim="listQuery.fver" clearable class="filter-item" style="width: 200px;" placeholder="请输入版本号"/>
      <!--<el-select v-model="listQuery.fver" clearable class="filter-item" filterable placeholder="请选择版本号">
        <el-option v-for="(key, value) in fscenetypeMap" :key="key" :label="key" :value="value"/>
      </el-select>-->
      <el-button class="filter-item" :style="{background:buttonColor.lookup,color:buttonColor.color}" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <!--<el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>-->
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <el-input v-model.trim="fsmartver" clearable class="filter-item" style="width: 200px;" placeholder="请输入版本号"/>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="smartverUpdate(fsmartver)">更新</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column :index="indexMethod" align="center" label="序" type="index" />
      <el-table-column align="center" label="机器码" prop="fmac" />
      <el-table-column align="center" label="版本号" prop="fver" />
      <!--<el-table-column align="center" label="执行结果" prop="fexeStatus">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.fexeStatus | fscenetypeFilter }}</el-tag>
        </template>
      </el-table-column>-->
      <el-table-column :formatter="dateFormat" align="center" label="更新时间" prop="fupddate" />
      <!--<el-table-column align="center" label="教室编号" prop="fpointNo" />-->
      <!--<el-table-column align="center" label="教师编号" prop="fteacherno" />-->

      <el-table-column align="center" width="200" label="操作" class-name="small-padding">
        <template slot-scope="scope">
          <el-button :style="{background:buttonColor.addprint,color:buttonColor.color}" size="mini" @click="handleUpdate(scope.row)">生成打印</el-button>
          <el-button :style="{background:buttonColor.delete,color:buttonColor.color}" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="80px" style="width: 450px; margin-left:30px;">
        <!--<el-row>
          <el-col :span="10">
            <el-form-item label="所属学校" prop="fsiteNo" style="width: 250px">
              <el-select v-model="dataForm.fsiteNo" :disabled="dialogStatus=='update'" clearable filterable placeholder="请选择">
                <el-option
                  v-for="item in fsiteNoBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10" style="padding-left: 80px">
            <el-form-item label="场景名称" prop="fscenename" style="width: 250px">
              <el-input v-model="dataForm.fscenename"/>
            </el-form-item>
          </el-col>
        </el-row>-->
        <!--<el-row>
          <el-col :span="10">
            <el-form-item class="el-form-item-small" label="执行结果" prop="fexeStatus" style="width: 250px">
              <el-select v-model="dataForm.fexeStatus" class="filter-item" placeholder="请选择场景类型" @change="changeSceneType(dataForm.fexeStatus)">
                <el-option v-for="(key, value) in fscenetypeMap" :key="key" :label="key" :value="value"/>
              </el-select>
            </el-form-item>
          </el-col>-->
        <!--<el-col :span="10" style="padding-left: 80px">
            <el-form-item v-show="dataForm.fscenetype==2" label="空气项目" prop="fairitem" style="width: 250px">
              <el-select v-model="dataForm.fairitem" clearable filterable placeholder="请选择">
                <el-option
                  v-for="item in sTsAiritemOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-row>
          <el-col :span="6">
            <el-form-item v-show="dataForm.fscenetype==2" label="空气项目" prop="fairitem" style="width: 250px">
              <el-select v-model="dataForm.fairitem" clearable filterable placeholder="请选择">
                <el-option
                  v-for="item in sTsAiritemOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="padding-left: 70px">
            <el-form-item v-show="dataForm.fscenetype==2" prop="fwhere" style="width: 150px">
              <!--<el-input v-model="dataForm.fwhere"/>-->
              <el-select v-model="dataForm.fwhere" class="filter-item" placeholder="符号">
                <el-option v-for="(key, value) in symbolOptions" :key="key" :label="key" :value="value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="padding-left: 40px">
            <el-form-item v-show="dataForm.fscenetype==2" prop="fvalue" style="width: 150px">
              <el-input v-model="dataForm.fvalue"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item v-show="dataForm.fscenetype==1" label="执行日期" prop="fexecweekList" style="width: 250px">
              <el-select v-model="dataForm.fexecweekList" clearable multiple placeholder="请选择">
                <el-option label="全选" @click.native="selectAll"/>
                <el-option v-for="(key, value) in fexecweekOptions" :key="key" :label="key" :value="value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10" style="padding-left: 80px">
            <el-form-item v-show="dataForm.fscenetype==1" label="更新时间" prop="fupddate" style="width: 250px">
              <el-time-picker v-model="dataForm.fupddate" type="datetime" placeholder="选择日期时间" format="HH:mm"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-tabs type="border-card">
        <el-tab-pane label="设备列表">
          <div class="filter-container">
            <el-button class="filter-item" :style="{background:buttonColor.add,color:buttonColor.color}" icon="el-icon-edit" @click="handleUpdate1">添加设备</el-button><!--handleCreate-->
            <el-table v-loading="listLoading" :data="dataForm.sTsEquipmentList" element-loading-text="正在查询中。。。" border fit highlight-current-row>
              <el-table-column :index="indexMethod" align="center" label="序" type="index"/>
              <el-table-column align="center" label="设备" prop="feuipmentname"/>
              <el-table-column align="center" label="指令" prop="finstructions"/>
              <el-table-column align="center" width="140" label="操作" class-name="small-padding">
                <template slot-scope="scope">
                  <el-button :style="{background:buttonColor.delete,color:buttonColor.color}" size="mini" @click="handleDelete1(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane label="楼层列表">
          <div v-show="dataForm.frange==1" class="filter-container">
            <el-button class="filter-item" :style="{background:buttonColor.add,color:buttonColor.color}" icon="el-icon-edit" @click="handleUpdate2(dataForm.fsiteNo)">添加楼层</el-button>
            <el-table v-loading="listLoading" :data="dataForm.atsPoints" element-loading-text="正在查询中。。。" border fit highlight-current-row>

              <el-table-column :index="indexMethod" align="center" label="序" type="index"/>
              <el-table-column align="center" label="楼层名称" prop="fpointName"/>
              <el-table-column align="center" width="140" label="操作" class-name="small-padding">
                <template slot-scope="scope">
                  <el-button :style="{background:buttonColor.delete,color:buttonColor.color}" size="mini" @click="handleDelete2(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane label="教室列表">
          <div v-show="dataForm.frange==2" class="filter-container">
            <el-button class="filter-item" :style="{background:buttonColor.add,color:buttonColor.color}" icon="el-icon-edit" @click="handleUpdate2(dataForm.fsiteNo)">添加教室</el-button>
            <el-table v-loading="listLoading" :data="dataForm.atsPoints" element-loading-text="正在查询中。。。" border fit highlight-current-row>

              <el-table-column :index="indexMethod" align="center" label="序" type="index"/>
              <el-table-column align="center" label="教室名称" prop="fpointName"/>
              <el-table-column align="center" width="140" label="操作" class-name="small-padding">
                <template slot-scope="scope">
                  <el-button :style="{background:buttonColor.delete,color:buttonColor.color}" size="mini" @click="handleDelete2(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus1]" :visible.sync="dialogFormVisible1">
      <el-form ref="dataForm1" :rules="rules" status-icon label-position="left" label-width="110px" style="width: 400px; margin-left:50px;">
        <el-form-item class="el-form-item-small" label="设备类型" prop="feuipmenttype" style="width: 250px">
          <el-select v-model="feuipment" class="filter-item" placeholder="请选择设备类型" @change="getEqtActions(feuipment)">
            <el-option
              v-for="item in sTsEquipmentDictOptions"
              :key="item.value"
              :label="item.label"
              :value="item"/>
          </el-select>
        </el-form-item>
        <el-form-item class="el-form-item-small" label="设备指令" style="width: 250px">
          <el-select v-model="action" class="filter-item" placeholder="请选择设备指令">
            <el-option
              v-for="item in eqtActionOptions"
              :key="item.value"
              :label="item.label"
              :value="item"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="dialogFormVisible1 = false">取消</el-button>
        <el-button :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="addData">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus2]" :visible.sync="dialogFormVisible2">
      <el-form ref="dataForm2" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="110px" style="width: 400px; margin-left:50px;">
        <el-table ref="multipleTable" :data="atsPoints" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange2">
          <el-table-column type="selection" width="55"/>
          <el-table-column prop="fpointNo" label="教室编号" width="120"/>
          <el-table-column prop="fpointName" label="教室名称" show-overflow-tooltip/>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="dialogFormVisible2 = false">取消</el-button>
        <el-button :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="addData2">确定</el-button>
      </div>
    </el-dialog>

    <!--二维码-->
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus2]" :visible.sync="dialogFormVisible3">
      <section id="printMer2" ref="prints">
        <div :model="dataForm" class="dashboard-editor-container" style="margin-left: 240px">
          <el-row>
            <!-- <el-col>
              <qrcode :value="dataForm.fmac" :options="{ size: 100 }"/>
            </el-col> -->
          </el-row>
          <el-row>
            <el-col>
              <h3 style="margin-left: 10px; margin-top: 1px">{{ dataForm.fmac }}</h3>
            </el-col>
          </el-row>
        </div>
      </section>
      <div slot="footer" class="dialog-footer">
        <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="dialogFormVisible3 = false">取消</el-button>
        <el-button v-print="'#printMer2'" :style="{background:buttonColor.print,color:buttonColor.color}">打印</el-button><!-- @click="addData2"-->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listScenario, createScenario, updateScenario, verUpdate, deleteScenario, eqtActions } from '@/api/smartversion'
import Pagination from '@/components/Pagination'
import moment from 'moment/moment'
// import QRcode from '@xkeshi/vue-qrcode'

const fscenetypeMap = {
  0: '失败',
  1: '成功'
}

const frangeMap = {
  0: '学校',
  1: '楼层',
  2: '教室'
}

const symbolOptions = {
  '>=': '>=',
  '<=': '<=',
  '>': '>',
  '<': '<',
  '=': '='
}

const fexecweekOptions = {
  '1': '周一',
  '2': '周二',
  '3': '周三',
  '4': '周四',
  '5': '周五',
  '6': '周六',
  '7': '周日'
}

export default {
  name: 'Alarm',
  // qrcode: QRcode
  components: { Pagination,  },
  filters: {
    fscenetypeFilter(type) {
      return fscenetypeMap[type]
    },
    frangeFilter(type) {
      return frangeMap[type]
    },
    fexecweekFilter(type) {
      return fexecweekOptions[type]
    }
  },
  data() {
    return {
      fsmartver: null,
      multipleSelection: [],
      multipleSelection2: [],
      multiple2: [],
      list: null,
      total: 0,
      fsiteNoBelongOptions: null,
      sTsAiritemOptions: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        fariname: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      updateversionVo: {
        fmacList: undefined,
        fver: undefined
      },
      fscenetypeMap,
      frangeMap,
      symbolOptions,
      fexecweekOptions,
      dataForm: {
        fmac: undefined,
        fairitem: undefined,
        fver: undefined,
        fupddate: undefined
        // fscenename: undefined,
      },
      feuipment: '',
      action: null,
      sTsEquipmentDictOptions: [],
      eqtActionOptions: [],
      atsPoints: [],
      dialogFormVisible: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      dialogStatus: '',
      dialogStatus1: '',
      dialogStatus2: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        /* fscenename: [
          { required: true, message: '场景名称不能为空', trigger: 'blur' }
        ],*/
        fver: [
          { required: true, message: '版本号不能为空', trigger: 'blur' }
        ],
        fupddate: [
          { required: true, message: '更新时间不能为空', trigger: 'blur' }
        ]
      },
      permissionDialogFormVisible: false,
      systemPermissions: null,
      assignedPermissions: null,
      permissionForm: {
        roleId: undefined,
        permIds: []
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    formatStatus: function(row, column) {
      return row.fsiteState === 1 ? '启用' : '禁用'
    },
    dateFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null || date === '') {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    formatSite: function(row, column) {
      for (let i = 0; i < this.fsiteNoBelongOptions.length; i++) {
        if (row.fsiteNo === this.fsiteNoBelongOptions[i].value) {
          return this.fsiteNoBelongOptions[i].label
        }
      }
      return ''
    },
    formatFairitem: function(row, column) {
      for (let i = 0; i < this.sTsAiritemOptions.length; i++) {
        if (row.fairitem === this.sTsAiritemOptions[i].value) {
          return this.sTsAiritemOptions[i].label
        }
      }
      return ''
    },
    handleSelectionChange2(val) {
      this.multipleSelection2 = val
    },
    getEqtActions(feuipment) {
      this.eqtActionOptions = []
      this.action = ''
      eqtActions(feuipment.value)
        .then(response => {
          this.eqtActionOptions = response.data.data.list
        })
        .catch(() => {
          this.eqtActionOptions = []
        })
    },
    addData() {
      this.dialogFormVisible1 = false
      for (var i in this.dataForm.sTsEquipmentList) {
        var eqt = this.dataForm.sTsEquipmentList[i]
        if (eqt.feuipmentid === this.feuipment.value && eqt.faction === this.action.value) {
          return
        }
      }
      this.dataForm.sTsEquipmentList.push(
        { feuipmentid: this.feuipment.value, feuipmentname: this.feuipment.label, faction: this.action.value, finstructions: this.action.label })
    },
    addData2() {
      this.dialogFormVisible2 = false
      for (var i in this.multipleSelection2) {
        var atsPoint = this.multipleSelection2[i]
        var canAdd = true
        for (var j in this.dataForm.atsPoints) {
          if (atsPoint.fpointNo === this.dataForm.atsPoints[j].fpointNo) {
            canAdd = false
            break
          }
        }
        if (canAdd) {
          atsPoint.fwarringno = this.dataForm.fwarringno
          this.dataForm.atsPoints.push(atsPoint)
          this.multiple2.push(atsPoint)
        }
      }
    },
    changeSceneType(fscenetype) {
      if (fscenetype === 1) {
        this.dataForm.fairitem = null
        this.dataForm.fwhere = null
        this.dataForm.fvalue = null
      } else if (fscenetype === 2) {
        this.dataForm.fexecweekList = []
        this.dataForm.fupddate = null
      }
    },
    changeRange() {
      this.dataForm.atsPoints = []
      this.multipleSelection2 = []
    },
    formatDate(fupddate) {
      var strs = fupddate.split(' ')
      var dateStr = 'Jan 01 ' + strs[1] + ':' + strs[0] + ':00 CST 1970 GMT+0800'
      return new Date(dateStr)
    },
    getList() {
      this.listLoading = true
      listScenario(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.list.forEach(v => {
            if (v.fscenetype === 1) {
              v.fupddate = this.formatDate(v.fupddate)
            }
          })
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        fmac: undefined,
        // fscenename: undefined,
        fver: undefined,
        fupddate: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataForm.fscenetype === '1' && (this.dataForm.fexecweekList === undefined || this.dataForm.fexecweekList.length === 0)) {
            this.$notify.info({
              title: '失败',
              message: '执行日期至少选择一天'
            })
            return
          }
          createScenario(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加预设场景成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.msg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      debugger
      this.dataForm = Object.assign({}, row)
      // this.dataForm.fscenetype = row.fscenetype.toString()
      // this.dataForm.frange = row.frange.toString()
      // this.dialogStatus = 'update'
      this.dialogFormVisible3 = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate1() {
      this.dialogStatus1 = 'update'
      this.dialogFormVisible1 = true
      this.feuipment = ''
      this.eqtActionOptions = []
      this.action = ''
      this.$nextTick(() => {
        this.$refs['dataForm1'].clearValidate()
      })
    },
    handleUpdate2(fsiteNo) {
      if (fsiteNo == null) {
        this.$notify.info({
          title: '',
          message: '请先选择学校'
        })
        return
      }
      this.dialogStatus2 = 'update'
      this.dialogFormVisible2 = true
      this.multipleSelection2 = []
      this.$nextTick(() => {
        this.$refs['dataForm2'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataForm.fscenetype === '1' && (this.dataForm.fexecweekList === undefined || this.dataForm.fexecweekList.length === 0)) {
            this.$notify.info({
              title: '失败',
              message: '执行日期至少选择一天'
            })
            return
          }
          updateScenario(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.fmac === this.dataForm.fmac) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新场景设定成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.msg
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否要删除该预设场景', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteScenario(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除预设场景成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.msg
            })
          })
      })
    },
    smartverUpdate(fsmartver) {
      if (fsmartver == null) {
        this.$notify.info({
          title: '',
          message: '请输入版本号'
        })
        return
      }
      if (this.list == null || this.list.size === 0) {
        this.$notify.info({
          title: '',
          message: '没有需要更新的smart'
        })
        return
      }
      this.$confirm('是否要更新smart版本', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateversionVo.fmacList = this.list
        this.updateversionVo.fver = fsmartver
        verUpdate(this.updateversionVo)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '更新smart版本成功'
            })
            // const index = this.list.indexOf(row)
            // this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.msg
            })
          })
      })
    },
    handleDelete1(row) {
      this.dataForm.sTsEquipmentList.pop(row)
    },
    handleDelete2(row) {
      this.dataForm.atsPoints.pop(row)
    },
    indexMethod(index) {
      index = index + 1
      return index
    },
    selectAll() {
      if (this.dataForm.fexecweekList.length < 7) {
        this.dataForm.fexecweekList = []
        for (var option in fexecweekOptions) {
          this.dataForm.fexecweekList.push(option)
        }
      } else {
        this.dataForm.fexecweekList = []
      }
    }
  }
}
</script>
